<template>
  <div>
    <a-modal
      :maskClosable="false"
      :title="title"
      :width="1300"
      :bodyStyle="{
        padding: '0 24px'
      }"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭">
      <a-card :bordered="false" :bodyStyle="{
          padding: '10px 24px'
        }">
        <div style="display: flex;align-item: center;margin-bottom: 15px">
          <span style="line-height: 32px">档案编号：</span>
          <a-input
            :style="{width:'150px'}"
            placeholder="请输入档案编号"
            v-model="queryParam.fileNo"
          ></a-input>
          <!-- <span style="margin-left: 15px;line-height: 32px">密级：</span>
              <j-dict-select-tag type="list" v-model="queryParam.secrecyLevel"
                                     dictCode="secrecy_level" style="width:200px"  placeholder="请选择密级"/> -->
          <span style="margin-left: 15px;line-height: 32px">档案所属团队：</span>
          <select-team-input  :multi="false" :tdlx="3" :teamType="0" queryType="all" v-model="queryParam.teamId" style="width:200px;display: inline-block;"  />

          <span style="margin-left: 20px;line-height: 32px">项目名称：</span>
          <select-project-input :style="{width:'150px'}" v-model="queryParam.projectId" placeholder="请选择关联项目" />

          <a-button @click="searchByquery" style="margin-left: 20px;" type="primary">查询</a-button>
          <a-button @click="searchReset(1)" style="margin-left: 20px" icon="redo">重置</a-button>
        </div>
        <a-table
          ref="table"
          rowKey="id"
          :scroll="scrollTrigger"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :rowSelection="{selectedRowKeys: selectedRowKeys,onSelectAll:onSelectAll,onSelect:onSelectOne, onChange: onSelectChange,type: getType}"
          @change="handleTableChange"
          class="j-table-force-nowrap"
          wrapClassName="ant-modal-cust-warp"
        >
          <span slot="projectId" slot-scope="text,record">
            <a @click="projectDetail(record.projectId)">{{ text }}</a>
          </span>
<!--          <a slot="projectId" slot-scope="text, record" @click="projectDetail(record.projectId)">{{ text }}</a>-->

          <span slot="fileNo" slot-scope="text, record">
            <a @click="onDetail(record)">{{ text }}</a>
          </span>
        </a-table>

        <!-- 详情开始 -->
        <a-modal
          :maskClosable="false"
          title="项目存档详情"
          :width="1200"
          :bodyStyle="{
            padding: '0 24px'
          }"
          :visible="visibleDetail"
          @cancel="handleCancelDetail"
          cancelText="关闭">
          <erp-project-archive-file-form ref="realForm" :disabled="true" normal />
          <template slot="footer">
            <a-button @click.stop="handleCancelDetail">关闭</a-button>
          </template>
        </a-modal>

        <!-- 项目详情开始 -->
        <erp-project-report-modal  ref="projectModalForm"></erp-project-report-modal>
        <!-- 项目详情结束 -->
      </a-card>
    </a-modal>
  </div>
</template>

<script>
  import {filterObj} from '@/utils/util';
  import {queryDepartTreeList, searchByKeywords} from '@/api/api'
  import {getAction} from '@/api/manage'
  import { mapGetters } from 'vuex';
  import SelectTeamInput from '../SelectTeamInput';
  import SelectProjectInput from '../SelectProjectInput'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput';


  export default {
    name: "SelectProjectArchiveInputModal",
    components: {
      SelectTeamInput,
      SelectProjectInput,
      SelectCompanyInput,
      ErpProjectArchiveFileForm: () => import('@/views/erp/omc/projectarchive/modules/ErpProjectArchiveFileForm'),
      ErpProjectReportModal: () => import('@/views/erp/report/project/modules/ErpProjectReportModal'),
    },
    props: ['multi', 'urlList','teamId','applicant','docBigCategory','docSmallCategory'],
    data() {
      return {
        title: "关联项目存档清单",
        queryParam: {},
        visibleDetail: false,
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            },
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title: '档案编号',
            align: "center",
            dataIndex: 'fileNo',
            scopedSlots: { customRender: 'fileNo' },
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'项目名称',
            align:"center",
            dataIndex: 'projectId_dictText',
            scopedSlots: { customRender: 'projectId' },
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'项目编号',
            align:"center",
            dataIndex: 'projectNo',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'签订单位',
            align:"center",
            dataIndex: 'signUnit_dictText',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          // {
          //   title:'申请人部门',
          //   align:"center",
          //   dataIndex: 'proposerDeptId_dictText',
          //   customCell: (record, index)=> {
          //     let that=this;
          //     return {
          //       on: {
          //         click: () => {
          //           console.log(record, index)
          //           that.selectedRowKeys = [];
          //           that.selectedRowKeys.push(record.id);
          //           that.choseObj = [];
          //           that.choseObj.push(record);
          //         }
          //       }
          //     }
          //   }
          // },
          {
            title:'档案所属团队',
            align:"center",
            dataIndex: 'archiveBelongingTeam_dictText',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'业务名称',
            align:"center",
            dataIndex: 'businessName_dictText',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'项目负责人',
            align:"center",
            dataIndex: 'projectLeader_dictText',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'密级',
            align:"center",
            dataIndex: 'secrecyLevel_dictText',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'存档人',
            align:"center",
            dataIndex: 'archivePerson_dictText',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
          {
            title:'存档位置',
            align:"center",
            dataIndex: 'archiveLocation',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    console.log(record, index)
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.choseObj = [];
                    that.choseObj.push(record);
                  }
                }
              }
            }
          },
        
        ],
        url: {},
        dataSource: [],
        choseObj: [],
        departTree: [],
        selectedKeys: [],
        iExpandedKeys: [],
        orgCode: '',
        loading: false,
        treeData: [],
        checkedKeys: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter: {
          column: 'createTime',
          order: 'desc',
        },
        scrollTrigger: {x:true},
        selectedRowKeys: [],
        selectionRows: [],
        visible: false,
        toggleSearchStatus: false,
        dictOptions:{},
        // 穿透项目名称
        queryProjectById: '/api/erp/project/report/erpProjectReport/queryById',
      }
    },
    created() {
      this.loadData();
      // 该方法触发屏幕自适应
      this.resetScreenSize();
      this.refresh();
      this.initSource();
      //加载数据字典信息
      this.initDictConfig();
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        console.log("multi: ", this.multi);
        return this.multi == true ? 'checkbox' : 'radio';
      }
    },
    watch:{
      'teamId'(val){
        if(!!val){
          console.log(this.teamId)
          this.queryParam.teamId=this.teamId;
          this.loadData(1);
        }
      },
      'applicant'(val){
        if(!!val){
          this.queryParam.companyId=this.applicant;
          this.loadData(1);
        }
      },
      'docBigCategory'(val){
        console.log(val);
        if(!!val){
          this.queryParam.archiveMajorCategory = this.docBigCategory
          this.loadData();
        }
      },
      'docSmallCategory'(val){
        if(!!val){
          this.queryParam.archiveMinorCategory = this.docSmallCategory
          this.loadData();
        }
      }
    },
    methods: {
      ...mapGetters(['userInfo']),
      onDetail(record) {
        this.visible = false
        this.visibleDetail = true
        this.$nextTick(()=>{
          this.$refs.realForm.edit(record);
        });
      },
      handleCancelDetail() {
        this.visible = true
        this.visibleDetail = false
      },
      initDictConfig(){
        initDictOptions('erp_omc_project,project_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectId', res.result)
          }
        })
        initDictOptions('erp_omc_prepare_project,mc,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'preprojectId', res.result)
          }
        })
      },
      projectDetail(id) {
        const that = this
        this.$nextTick(() => {
          console.log('项目一览表数据id为：',id)
          getAction(this.queryProjectById, { id }).then((res) => {
            if (res.success) {
              console.log('请求结果为：',res.result)
              const model = res.result
              that.$refs.projectModalForm.getDetail(model);
              that.$refs.projectModalForm.title = '项目一览表';
            }
          })
        })
      },
      add(selectObj, ids) {
        this.visible = true;
        this.edit(selectObj, ids);
      },
      edit(selectObj, ids) {

        if (!ids) {
          this.selectedRowKeys = []
        } else {
          this.selectedRowKeys = ids;
        }
        if (!selectObj) {
          this.selectionRows = []
        } else {
          this.selectionRows = selectObj;
          this.choseObj = selectObj;
        }
        if (ids == null && selectObj == null) {
          this.selectionRows = [];
          this.choseObj = [];
          this.selectedRowKeys = [];
        }
      },
      loadData(arg) {
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }

        var params = this.getQueryParams();//查询条件
        //查询已完成的
        params.archiveMajorCategory=this.docBigCategory
        params.archiveMinorCategory=this.docSmallCategory
        getAction(this.urlList, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records;
            this.ipagination.total = res.result.total;
            if (this.orgCode === '') {
              //第一次打开
            } else {
              for (var i = 0; i < this.dataSource.length; i++) {
                console.log(this.dataSource[i]);
                for (var j = 0; j < this.choseObj.length; j++) {
                  if (this.choseObj[j].id == this.dataSource[i].id) {
                    this.selectionRows.push(this.dataSource[i]);
                    this.selectedRowKeys.push(this.dataSource[i].id);
                    break;
                  }
                }
              }
            }
            //判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
          }
        })
      },
      loadTree() {
        var that = this
        that.treeData = []
        that.departTree = []
        queryDepartTreeList().then((res) => {
          if (res.success) {
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.treeData.push(temp)
              that.departTree.push(temp)
              that.setThisExpandedKeys(temp)
              // console.log(temp.id)
            }
            this.loading = false
          }
        })
      },
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return filterObj(param);
      },
      getQueryField() {
        let str = "id,";
        for (let a = 0; a < this.columns.length; a++) {
          str += "," + this.columns[a].dataIndex;
        }
        return str;
      },
      onSelectAll(selected, selectedRows, changeRows) {
        if (selected === true) {
          for (var a = 0; a < changeRows.length; a++) {
            this.choseObj.push(changeRows[a]);
          }
        } else {
          for (var b = 0; b < changeRows.length; b++) {
            this.choseObj.splice(this.choseObj.indexOf(changeRows[b]), 1);
          }
        }
        // console.log(selected, selectedRows, changeRows);
      },
      onSelectOne(record, selected) {
        console.log(record,selected)
        if (selected === true) {
          if (this.multi) { //多选
            this.choseObj.push(record);
          } else {  //单选
            this.choseObj = [];
            this.choseObj.push(record);
          }
        } else {
          if (this.multi) { //多选
            var index = -1;
            for (var i = 0; i < this.choseObj.length; i++) {
              if (this.choseObj[i].id == record.id) {
                index = i;
                break;
              }
            }
            //console.log();
            if (index >= 0) {
              this.choseObj.splice(index, 1);
            }
          } else { //单选
            this.choseObj = [];
          }
        }
      }, initSource() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
        this.choseObj = [];
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        console.log(this.selectedRowKeys);
        this.selectionRows = selectionRows;
      },
      searchReset() {
        let that = this;
        Object.keys(that.queryParam).forEach(function (key) {
          if(!!that.teamId && key == 'teamId'){
            that.queryParam[key] = that.queryParam[key]
          }else if(!!that.applicant && key == 'companyId'){
            that.queryParam[key] = that.queryParam[key]
          }else{
            that.queryParam[key] = null;
          }
        });
        that.loadData(1);
      },
      handleTableChange(pagination, filters, sorter) {
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.loadData();
      },
      handleCancel() {
        this.selectionRows = [];
        this.selectedRowKeys = [];
        this.visible = false;
      },
      handleOk() {
        this.$emit("choseObj", this.choseObj);
        this.handleCancel();
      },
      searchByquery() {
        this.loadData(1);
      },
      handleToggleSearch() {
        this.toggleSearchStatus = !this.toggleSearchStatus;
      },
      onSearch(value) {
        let that = this
        if (value) {
          searchByKeywords({keyWord: value}).then((res) => {
            if (res.success) {
              that.departTree = []
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                that.departTree.push(temp)
              }
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          that.loadTree()
        }

      },
      setThisExpandedKeys(node) {
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      refresh() {
        this.loading = true
        this.loadTree()
      },
      onSelect(selectedKeys, e) {
        if (this.selectedKeys[0] !== selectedKeys[0]) {
          this.selectedKeys = [selectedKeys[0]];
        }
        let record = e.node.dataRef;
        // this.selectionRows.push(record.id);
        this.onClearSelected();
        this.open(record);
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
      },
      open(record) {
        console.log(record);
        this.orgCode = record.orgCode;
        this.loadData(1);
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = {x: 800};
        } else {
          this.scrollTrigger = {};
        }
      }, allObj() {
        this.selectedKeys = [];
        this.onClearSelected();
        this.orgCode = null;
        this.loadData(1);
      }
    }
  }
</script>
<style scoped>
  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  .anty-img-wrap {
    height: 25px;
    position: relative;
  }

  .anty-img-wrap > img {
    max-height: 100%;
  }

</style>